package emulator

import (
	"bytes"
	"config"
	"fmt"
	"log"
	"mail"
	"net/http"
	"time"
)

const (
	// serverUrl = "http://127.0.0.1:4002"
	// userAccount  = "test12"
	// userpassword = "123456"
	subject = "llwant server monitor"
)

func startUsers(serverUrl string) {
	simulateUser(serverUrl)
	ticker := time.NewTicker(2 * time.Minute)
	for {
		select {
		case <-ticker.C:
			simulateUser(serverUrl)
		}
	}
}

// func simulateUsers() {
// 	log.Println("start simulate users")
// 	for _, serverUrl := range userservers {
// 		simulateUser(serverUrl)
// 	}
// }

func simulateUser(serverUrl string) {
	tk, uniqueId, err := login(serverUrl)
	if err != nil {
		//TODO:
		//send message
		errMsg := fmt.Sprintf("err: %s login %s, %v", config.Account, serverUrl, err)
		mail.SendMail(subject, errMsg)

		log.Println(errMsg)
		return
	}

	if tk == "" || uniqueId == "" {
		log.Println(`tk == "" || uniqueId == ""`)
		//TODO:
		//send message
		errMsg := fmt.Sprintf("err: %s login %s, tk or uniqueId is empty", config.Account, serverUrl)
		mail.SendMail(subject, errMsg)
		return
	}
	//test(serverUrl,tk,uniqueId)
}

func login(serverUrl string) (tk string, uniqueId string, err error) {
	// log.Println("start login")
	var jsonStr = []byte(`{"account":"709268224@qq.com","password":"qq123456"}`)
	client := &http.Client{Timeout: time.Second * 60}
	req, err := http.NewRequest("SET", serverUrl+"/bleLogin", bytes.NewBuffer(jsonStr))

	resp, err := client.Do(req)
	if err != nil {
		log.Println("login err: ", err)
		return
	}

	if resp.StatusCode != 200 {
		log.Println("resp.StatusCode != 200")
		err = fmt.Errorf("resp.StatusCode != 200")
		return
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		// log.Println("login errorcode: ", errcode)
		err = fmt.Errorf("errorCode is %v", errcode)
		return
	}

	// log.Println("body: ", string(message))
	token := resp.Header.Get("tk")
	myid := resp.Header.Get("id")

	// log.Println("login reply:", loginReply)
	log.Printf("login %s success", serverUrl)
	return token, myid, nil
}

func test(serverUrl string, tk string, uniqueId string) error {
	var jsonStr = []byte(`{"account":"709268224@qq.com","personalId":"1","bmi":"20","weight":"55","height":"178"}`)
	client := &http.Client{Timeout: time.Second * 60}
	req, err := http.NewRequest("SET", serverUrl+"/bleSetHealthInfo", bytes.NewBuffer(jsonStr))

	req.Header.Add("tk", tk)
	req.Header.Add("uniqueId", uniqueId)

	resp, err := client.Do(req)
	if err != nil {
		log.Println("err: ", err)
		return err
	}

	if resp.StatusCode != 200 {
		log.Println("resp.StatusCode != 200")
		err = fmt.Errorf("resp.StatusCode != 200")
		return err
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Println("errorcode: ", errcode)
		err = fmt.Errorf("error code is %s", errcode)
		return err
	}

	body := make([]byte, 1024)
	read, err := resp.Body.Read(body)
	if err != nil && read < 1 {
		log.Println("read message body err: ", err)
		return err
	}

	body = body[:read]
	log.Println("body: ", string(body))

	// log.Println("body: ", string(message))

	// type Reply struct {
	// 	Controllers []Controller `json:"devices"`
	// }

	return nil
}

